package com.example.permissionsystem1_1.businessFunction.service.interfaces.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.permissionsystem1_1.businessFunction.dao.entity.po.*;
import com.example.permissionsystem1_1.businessFunction.dao.repository.*;
import com.example.permissionsystem1_1.businessFunction.service.converter.UserInfoServiceConverter;
import com.example.permissionsystem1_1.businessFunction.service.entity.reqModel.userInfoReqModel.*;
import com.example.permissionsystem1_1.businessFunction.service.entity.rspModel.userInfoRspModel.*;
import com.example.permissionsystem1_1.businessFunction.service.interfaces.UserInfoService;
import com.example.permissionsystem1_1.common.businessFunction.BaseServiceImpl;
import com.example.permissionsystem1_1.system.annotation.aspectAnnotation.SuperManageOperationAspectAnnotation;
import com.example.permissionsystem1_1.system.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserInfoServiceImpl extends BaseServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserFunctionRecordDao userFunctionRecordDao;
    @Autowired
    private DepartmentUserDao departmentUserDao;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public UserInfoInsertRspModel insert(UserInfoInsertReqModel reqModel) {
        UserInfoPo po= UserInfoServiceConverter.convertReqModelToPo(reqModel);
        Integer resultInt=-1;
        //字段重复性校验:如果重复,则会将po变成空,从而阻止接下去的数据库操作
        List<String> fieldNames=new ArrayList<>();
        fieldNames.add("userName");
        try {
            po=fieldsRepeatCheck(userInfoDao,"selects",po,fieldNames,"insert");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            po=null;
        }
        if(po!=null){
            resultInt=userInfoDao.insert(po);
        }
        return UserInfoServiceConverter.covertToRspModel(resultInt);
    }

//    @Override
//    public TestInsertBatchRspModel insertBatch(TestInsertBatchReqModel reqModel) {
//        List<TestPo> pos=TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(pos!=null&&pos.size()>0){
//            resultSum=testDao.insertBatch(pos);
//        }
//        return TestServiceConverter.covertToInsertBatchRspModel(resultSum);
//    }

    @Override
    @Transactional
    @SuperManageOperationAspectAnnotation
    public UserInfoDeleteByIdRspModel deleteById(UserInfoDeleteByIdReqModel reqModel) {
        UserInfoPo po= UserInfoServiceConverter.convertReqModelToPo(reqModel);
        //关联数据清理:根据用户id删除当前用户的部门用户关联记录和用户角色关联记录
        deleteDepartmentUserAndUserRoleByUserId(po.getId());
        //功能权限的重建:将这个用户的用户功能表的关联记录删除
        reconstructionUserFunctionsByUserId(po.getId());

        return UserInfoServiceConverter.covertToDeleteByIdRspModel(userInfoDao.deleteById(po.getId()));
    }

//    @Override
//    public TestDeletesRspModel deletes(TestDeletesReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null){
//            resultSum=testDao.deletes(po);
//        }
//        return TestServiceConverter.covertToDeletesRspModel(resultSum);
//    }

//    @Override
//    public TestDeleteBatchByIdsRspModel deleteBatchByIds(TestDeleteBatchByIdsReqModel reqModel) {
//        TestPo po=TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getIds()!=null&&po.getIds().size()>0){
//            resultSum=testDao.deleteBatchByIds(po.getIds());
//        }
//        return TestServiceConverter.covertToDeleteBatchByIdsRspModel(resultSum);
//    }

    @Override
    @SuperManageOperationAspectAnnotation
    public UserInfoUpdateByIdRspModel updateById(UserInfoUpdateByIdReqModel reqModel) {
        UserInfoPo po= UserInfoServiceConverter.convertReqModelToPo(reqModel);
        Integer resultInt=-1;
        //字段重复性校验:如果重复,则会将po变成空,从而阻止接下去的数据库操作
        List<String> fieldNames=new ArrayList<>();
        fieldNames.add("userName");
        try {
            po=fieldsRepeatCheck(userInfoDao,"selects",po,fieldNames,"update");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            po=null;
        }
        if(po!=null){
            resultInt=userInfoDao.updateById(po);
        }
        return UserInfoServiceConverter.covertToUpdateByIdRspModel(resultInt);
    }

//    @Override
//    public TestUpdatesRspModel updates(TestUpdatesReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getByPo()!=null&&po.getSetPo()!=null){
//            resultSum=testDao.updates(po.getByPo(),po.getSetPo());
//        }
//        return TestServiceConverter.covertToUpdatesRspModel(resultSum);
//    }

//    @Override
//    public TestUpdateBatchByIdsRspModel updateBatchByIds(TestUpdateBatchByIdsReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getIds()!=null&&po.getIds().size()>0){
//            resultSum=testDao.updateBatchByIds(po);
//        }
//        return TestServiceConverter.covertToUpdateBatchByIdsRspModel(resultSum);
//    }

    @Override
    @SuperManageOperationAspectAnnotation
    public UserInfoSelectByIdRspModel selectById(UserInfoSelectByIdReqModel reqModel) {
        UserInfoPo po= UserInfoServiceConverter.convertReqModelToPo(reqModel);
        if(po!=null&&po.getId()!=null){
            po=userInfoDao.selectById(po.getId());
        }
        return UserInfoServiceConverter.covertToSelectByIdRspModel(po);
    }

    @Override
    public UserInfoSelectsRspModel selects(UserInfoSelectsReqModel reqModel) {
        UserInfoPo po= UserInfoServiceConverter.convertReqModelToPo(reqModel);
        List<UserInfoPo> pos=new ArrayList<>();
        if(po!=null){
            pos=userInfoDao.selects(po);
        }
        return UserInfoServiceConverter.covertToSelectsModel(pos);
    }

//    @Override
//    public TestSelectBatchByIdsRspModel selectBatchByIds(TestSelectBatchByIdsReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        List<TestPo> pos=new ArrayList<>();
//        if(po!=null){
//            pos=testDao.selectBatchByIds(po.getIds());
//        }
//        return TestServiceConverter.covertToSelectBatchByIdsModel(pos);
//    }

    @Override
    public UserInfoSelectPageRspModel selectPage(UserInfoSelectPageReqModel reqModel) {
        UserInfoPo po=UserInfoServiceConverter.convertReqModelToPo(reqModel);
        if(po==null){
            return null;
        }
        Page page=new Page(reqModel.getPageNo(),reqModel.getPageSize());
        //默认按照年龄排序
        page.addOrder(OrderItem.asc("id"));
        IPage<UserInfoPo> iPagePo=userInfoDao.selectPage(page,po);
        return UserInfoServiceConverter.covertToSelectPageModel(iPagePo);
    }

    @Override
    public UserLoginRspModel userLogin(UserLoginReqModel reqModel) {
        UserInfoPo po=UserInfoServiceConverter.convertReqModelToPo(reqModel);
        if(po==null){//用户名或密码只填了一个,或者是其他原因为null
            return null;
        }
        List<UserInfoPo> userInfoPos=userInfoDao.selects(po);
        if(userInfoPos==null||userInfoPos.size()<=0){
            //用户名或密码错误,登录失败
            return null;
        }
        //查询该用户的全部权限,返回给前端用户按钮展示以及放入缓存中备用
        List<UserFunctionRecordPo> userFunctionRecordPos=userFunctionRecordDao.selectAllFunctionsByUserId(userInfoPos.get(0).getId());

        if(userFunctionRecordPos==null||userFunctionRecordPos.size()<=0){
            return null;//没有登录的权限,则直接返回null:登陆失败,禁止登录
        }
        Integer i=0;
        List<String> functionUrls=new ArrayList<>();
        for (UserFunctionRecordPo userFunctionRecordPo:userFunctionRecordPos) {
            if(userFunctionRecordPo.getFunctionUrl()!=null&&!"".equals(userFunctionRecordPo.getFunctionUrl())){//此权限对应url接口
                functionUrls.add(userFunctionRecordPo.getFunctionUrl());
            }
            if(userFunctionRecordPo.getFunctionId().equals(1l)){//有登录权限,允许登录
                i=1;
//                break;
            }
        }
        if(i==0){//如果没有登录的权限,则直接返回null:登陆失败,禁止登录
            return null;
        }
        //将登录成功的用户的信息放入缓存中:存入session中,用于身份认证和后端url接口权限判断
        HttpSession session=WebUtil.getSession();
        session.setAttribute("userId",userInfoPos.get(0).getId());
        session.setAttribute("functionUrls",functionUrls);


        return UserInfoServiceConverter.covertToUserLoginModel(userFunctionRecordPos,userInfoPos.get(0));
    }

    //**********本类的业务处理方法
    /** 关联数据清理:根据用户id删除当前用户的部门用户关联记录和用户角色关联记录 */
    private void deleteDepartmentUserAndUserRoleByUserId(Long userId){
        DepartmentUserPo departmentUserPo=new DepartmentUserPo();
        departmentUserPo.setUserId(userId);
        departmentUserDao.deletes(departmentUserPo);
        UserRolePo userRolePo=new UserRolePo();
        userRolePo.setUserId(userId);
        userRoleDao.deletes(userRolePo);
    }
    /** 功能权限的重建:根据用户id删除用户功能的全部功能 */
    private void reconstructionUserFunctionsByUserId(Long userId){
        UserFunctionRecordPo userFunctionRecordPo=new UserFunctionRecordPo();
        userFunctionRecordPo.setUserId(userId);
        userFunctionRecordDao.deletes(userFunctionRecordPo);
    }
}
